package com.daojia.daojiasync.Utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;


public class TimeUtils {
    private static final DateTimeFormatter[] SUPPORTED_FORMATTERS = {
            DateTimeFormatter.ISO_LOCAL_DATE_TIME,
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd"),
            DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
            DateTimeFormatter.ofPattern("yyyy/MM/dd")
    };

    public static long LocalDateTimeToTimestamp(LocalDateTime localDateTime) {
        if (localDateTime == null) throw new RuntimeException("LocalDateTimeToTimestamp 参数不能为空！");
        return localDateTime.atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();
    }

    public static LocalDateTime parseDateTime(String dateTimeStr) {
        if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
            throw new IllegalArgumentException("日期时间字符串不能为空");
        }

        String trimmedStr = dateTimeStr.trim();

        // 尝试各种格式
        for (DateTimeFormatter formatter : SUPPORTED_FORMATTERS) {
            try {
                if (formatter.equals(DateTimeFormatter.ISO_LOCAL_DATE_TIME) ||
                        formatter.toString().contains("HH")) {
                    // 包含时间的格式
                    return LocalDateTime.parse(trimmedStr, formatter);
                } else {
                    // 只包含日期的格式
                    return LocalDate.parse(trimmedStr, formatter).atStartOfDay();
                }
            } catch (DateTimeParseException e) {
                // 尝试下一个格式
                continue;
            }
        }

        throw new DateTimeParseException("无法解析日期时间字符串: " + dateTimeStr, dateTimeStr, 0);
    }
}
